import { Inject, InjectClient, Provide } from '@midwayjs/core';
import { LoginDTO } from '../dto/loginDto';
import { CachingFactory, MidwayCache } from '@midwayjs/cache-manager';
import * as svgCaptcha from 'svg-captcha';
import { v1 as uuid } from 'uuid';

@Provide()
export class LoginService {
  
  @InjectClient(CachingFactory,'default')
  midwayCache: MidwayCache;

  @Inject()



  async login(loginDto: LoginDTO) {
    const { username, password, captchaId, verifyCode } = loginDto;
    console.log(`output->`,username, password)
    // 校验验证码
    const checkV = await this.captchaCheck(captchaId, verifyCode);
    
    if (checkV) {
      // const user = await this.baseSys
    }else {
      throw new Error('验证码错误');
    }
  }

  
  /**
   * @description: 获取验证码
   * @param {string} type 验证码类型
   * @param {*} width 验证码尺寸宽度
   * @param {*} height 验证码尺寸高度
   * @param {*} color 验证码颜色
   * @return {*}
   */
  async captcha(type:string,width = 150,height = 50) {
    const svg = svgCaptcha.create({
      width,
      height,
      color:true
    });
    const result = {
      data: svg.data.replace(/"/g, "'"),
      captchaId: uuid(),
    }
    await this.midwayCache.set(`verify:img:${result.captchaId}`,svg.text.toLocaleUpperCase(),1800*1800);
    return result;
  }

  async captchaCheck(captchaId: string, verifyCode: string) {
    const rv = await this.midwayCache.get(`verify:img:${captchaId}`);

    if (!rv||!verifyCode||verifyCode.toLocaleUpperCase()!==rv) {
      return false
    }else{
      this.midwayCache.del(`verify:img:${captchaId}`);
    }
  }
}
